package com.llh.controller.excel;

import com.llh.controller.http.DailyTrade;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class Excel_Export_Free_Util <T>{
    static Logger logger = LogManager.getLogger(DailyTrade.class.getName());
    public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";// 默认日期格式
    public static final int DEFAULT_COLUMN_WIDTH = 17;// 默认列宽


    // 写入数据的起始行
    private int rowIndex;
    //开始列索引
    private int startClom;
    //结束列索引
    private int endClom;
 /*   // 需要提取样式所在的行号
    private int styleIndex;*/
    // 对象的字节码
    private Class clazz;
    // 对象中的所有属性
    private Field fields[];

    // 构造方法
    public Excel_Export_Free_Util(Class clazz, int rowIndex,int startClom,int endClom) {
        this.clazz = clazz;
        this.rowIndex = rowIndex;
        fields = clazz.getDeclaredFields();
        this.startClom = startClom;
        this.endClom  = endClom;
    }

    /**
     * 基于注解导出
     * response：响应对象，用于往浏览器导出数据(文件下载)
     * is：模板文件对应的输入流
     * objs：要导出的数据，即从数据库中查询的对象数据集合
     * fileName：导出的文件名(文件下载名)
     */
    public void export(File in, List<T> objs, File out,Integer[] dateCellIndex) throws Exception {
        String datePattern = DEFAULT_DATE_PATTERN;
        int minBytes = DEFAULT_COLUMN_WIDTH;
        FileOutputStream fileOutputStream = null;
        FileInputStream fileInputStream = null;
        SXSSFWorkbook sxssfWorkbook = null;
        try{
            // 根据模板创建工作簿(.xlsx)
            fileInputStream = new FileInputStream(in);
            XSSFWorkbook workbook1 = new XSSFWorkbook(fileInputStream);
            sxssfWorkbook = new SXSSFWorkbook(workbook1, 100);
            // 获得工作表
            Sheet sheet = sxssfWorkbook.getSheetAt(0);
//            // 获取公共样式
//            CellStyle[] styles = getTemplateStyles(sheet.getRow(styleIndex));
           /* // 单元格样式
            CellStyle cellStyle = sxssfWorkbook.createCellStyle();
            cellStyle.setAlignment(sxssfWorkbook.ALIGN_CENTER);
            cellStyle.setVerticalAlignment(sxssfWorkbook.VERTICAL_CENTER);
            cellStyle.setBorderTop(sxssfWorkbook.BORDER_THIN);
            cellStyle.setBorderRight(sxssfWorkbook.BORDER_THIN);
            cellStyle.setBorderBottom(sxssfWorkbook.BORDER_THIN);
            cellStyle.setBorderLeft(sxssfWorkbook.BORDER_THIN);
            Font cellFont = sxssfWorkbook.createFont();
            cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
            cellStyle.setFont(cellFont);
*/
            AtomicInteger datasAi = new AtomicInteger(rowIndex);
            // 遍历集合
            int num = 0;
            for (T t : objs) {
                // 创建每一行对象
                SXSSFRow row = (SXSSFRow)sheet.createRow(datasAi.getAndIncrement());
                for (int i = startClom; i <= endClom; i++) {
                    // 创建一个单元格对象(每一列)
                    SXSSFCell cell = (SXSSFCell)row.createCell(i);
                    /*//设置单元格样式
                    if (dateCellIndex != null && dateCellIndex.length > 0) {
                        for (Integer integer : dateCellIndex) {
                            if (i == integer) {
                                //设置为:自定义时间类型格式
                                DataFormat format = workbook.createDataFormat();// 日期格式化
                                CellStyle cellStyle = workbook.createCellStyle();
                                cellStyle.setDataFormat(format.getFormat(dateFormat));
                                cell.setCellStyle(cellStyle);
                            }
                        }
                    } else {
                        // 设置列的样式为模板中的样式
                        cell.setCellStyle(styles[i]);
                    }*/
                   /* if (dateCellIndex != null && dateCellIndex.length > 0) {
                        for (Integer integer : dateCellIndex) {
                            if (i == integer) {
                                //设置为:自定义时间类型格式
                                DataFormat format = sxssfWorkbook.createDataFormat();// 日期格式化
                                CellStyle cellStyle = sxssfWorkbook.createCellStyle();
                                cellStyle.setDataFormat(format.getFormat(datePattern));
                                cell.setCellStyle(cellStyle);
                            }
                        }
                    }*/
                    //给单元格赋值
                    // 遍历成员变量对象
                    SimpleDateFormat format = new SimpleDateFormat(datePattern);
                    for (Field field : fields) {
                        // 判断成员变量上是否使用了ExcelAttribute注解
                        if (field.isAnnotationPresent(ExcelAttribute.class)) {
                            // 暴露反射
                            field.setAccessible(true);
                            // 获得注解对象
                            ExcelAttribute ea = field.getAnnotation(ExcelAttribute.class);
                            if (i == ea.sort()) {
                                //field类型
                                Class<?> type = field.getType();
                                if(type.equals(Date.class)){
                                    cell.setCellValue(format.format( (Date)field.get(t)));
                                }else if(type.equals(Double.class)) {
                                    cell.setCellValue(new BigDecimal(field.get(t).toString()).setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                                }else{
                                    // 设置单元格内容为字符串
                                    cell.setCellValue(field.get(t).toString());
                                }
                            }
                        }
                    }

                }
                logger.info("插入一行,一插入:" + (++num));

            }
        }finally {
            fileOutputStream = new FileOutputStream(out);
            //将文件写出,不覆盖
            sxssfWorkbook.write(fileOutputStream);
            fileOutputStream.flush();
            if(fileInputStream!=null){
                fileInputStream.close();
            }
            if(fileOutputStream!=null){
                fileOutputStream.close();
            }

        }

    }

    /**
     * 获得指定行的单元格样式
     */
    public CellStyle[] getTemplateStyles(Row row) {
        CellStyle[] styles = new CellStyle[row.getLastCellNum()];
        for (int i = 0; i < row.getLastCellNum(); i++) {
            styles[i] = row.getCell(i).getCellStyle();
        }
        return styles;
    }

    // 省略 setters & getters ..................

}
